<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: yangweijie <yangweijiester@gmail.com> <code-tech.diandian.com>
// +----------------------------------------------------------------------

namespace addons\xjeyuncaslogin;
use app\common\controller\Addons;
require_once("CAS.php");

/**
 * cas登录插件
 * @author thinkphp
 */

class XjeyunCaslogin extends Addons {

	public $info = array(
		'name'        => 'XjeyunCaslogin',
		'title'       => 'cas登录',
		'description' => 'cas登录',
		'status'      => 1,
		'author'      => 'xjeyun',
		'version'     => '1.0',
	);

	public function install(){
		return true;
	}

	public function uninstall(){
		return true;
	}
	
	public function userLogin($data){

		$config = $this->getConfig();//获取配置信息
		if($config['is_allow']==0){
		//用户调试
		\phpCAS::setDebug();

		\phpCAS::client(CAS_VERSION_2_0,$config['cas_host'],intval($config['cas_port']),$config['cas_context'],false);

		// 这个是设置非SSL访问，在真实项目中不建议使用，不安全.
		// 如果PHP环境没有openssl拓展的话，可以添加这个来测试单点登录的效果
		\phpCAS::setNoCasServerValidation();
		//这里会检测服务器端的退出的通知，就能实现php和其他语言平台间同步登出了
		\phpCAS::handleLogoutRequests();

		if($data=="logout"){  //钩子：：退出
			\phpCAS::logout();
		}
		if($data=="login"){	//钩子：：登录
			if (!is_login()) {
				if (\phpCAS::checkAuthentication()) {  //判断是否登录
					//获取登陆的用户名
					$username = \phpCAS::getUser();
					$user = db("member")->where("username='{$username}'")->find();
					if (empty($user)) {
						$adduser['username'] = $username;
						$adduser['reg_time'] = time();
						$adduser['reg_ip'] = get_client_ip(1);
						$adduser['last_login_time'] = time();
						$adduser['last_login_ip'] = get_client_ip(1);
						$adduser['status'] = 1;
						$userid = db("member")->insertGetId($adduser);
						if ($userid) {
							$auth = array(
								'uid' => $userid,
								'username' => $username,
								'last_login_time' => $adduser['last_login_time'],
							);
						} else {
							$this->error("增加用户失败");
						}
					} else {
						$auth = array(
							'uid' => $user['uid'],
							'username' => $user['username'],
							'last_login_time' => time(),
						);
					}
					/* 记录登录SESSION和COOKIES */
					session('user_auth', $auth);
					session('user_auth_sign', data_auth_sign($auth));
				} else {
					// 访问CAS的验证
					\phpCAS::forceAuthentication();
				}
			}
		}
		//exit;
		}
	}
	public function thirdLogin(){
		$this->template('caslogin');
	}

}